from odoo import api, models, fields
from odoo.exceptions import UserError

class NbdProjectTaskStageChangeLog(models.Model):
    _name = "nbd.project.task.stage.change.log"
    _inherits = {"project.task":"project_task_id" }
    _description= "NBD 项目自定义任务流程变更记录"
    
    project_task_id = fields.Many2one("project.task",string="Related Task", required=True, ondelete='cascade')
    
    stage_commant = fields.Char(string='Stage Change Comment', required=True, size=60)
    current_stage_id = fields.Char(string='Current Stage Display ID')
    current_stage_display_name = fields.Char(string='Current Stage Display Name')
    next_stage_id = fields.Char(string='Next Stage Display Name')
    next_stage_display_name = fields.Char(string='Next Stage Display Name')

    def create(self, vals_list):
        # if not self.env.context.get('project_task_id') and not vals_list['project_task_id']:
        #     raise UserError("未找到项目主键，请联系系统管理员")
        
        if self.env.context.get('project_task_id') and self.env.context.get('next_stage_id'):
            vals_list['project_task_id'] = self.env.context.get('project_task_id')
            vals_list['current_stage_id'] = self.env.context.get('current_stage_id') if self.env.context.get('current_stage_id') else None
            vals_list['current_stage_display_name'] = self.env.context.get('current_stage_display_name') if self.env.context.get('current_stage_display_name')  else None
            vals_list['next_stage_id'] = self.env.context.get('next_stage_id') if self.env.context.get('next_stage_id')  else None
            vals_list['next_stage_display_name'] = self.env.context.get('next_stage_display_name') if self.env.context.get('next_stage_display_name')  else None
            # 使用事务方法更新A表的字段
            with self.env.registry.cursor() as cr:
                cr.execute('UPDATE project_task SET stage_id = %s WHERE id = %s', (vals_list['next_stage_id'], vals_list['project_task_id']))
                try:
                    cr.commit()
                finally:
                    cr.close()
            record = super().create(vals_list)
            return record